package cn.knightzz.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.knightzz.constant.RoleType;
import cn.knightzz.entity.SysRole;
import cn.knightzz.entity.SysUser;
import cn.knightzz.entity.SysUserRole;
import cn.knightzz.mapper.SysRoleMapper;
import cn.knightzz.mapper.SysUserMapper;
import cn.knightzz.mapper.SysUserRoleMapper;
import cn.knightzz.service.SysUserService;
import cn.knightzz.util.PasswordEncodeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author knightzz
 * @since 2021-04-09
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    SysUserMapper userMapper;

    @Resource
    SysRoleMapper roleMapper;


    @Resource
    SysUserRoleMapper userRoleMapper;

    @Override
    public SysUser getUserByUserName(String username) {
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.eq("username", username);
        return userMapper.selectOne(sysUserQueryWrapper);
    }

    @Override
    public Boolean addUser(SysUser user) {
        // 判断用户是否存在
        SysUser userByUsername = getUserByUserName(user.getUsername());
        if (ObjectUtil.isEmpty(userByUsername)) {
            // 对用户密码进行加密
            user.setPassword(PasswordEncodeUtil.encode(user.getPassword()));
            // 添加用户
            userMapper.insert(user);
            // 在用户角色关系表中添加相关数据
            // 封装用户关系信息
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(user.getType());
            // 插入数据
            userRoleMapper.insert(userRole);
            return true;
        }
        return false;
    }

    /**
     * 根据id查询用户信息
     *
     * @param id
     * @return
     */
    @Override
    public SysUser getUserById(Long id) {
        if (ObjectUtil.isNull(id)) {
            log.error("getUserById : id 为空 !");
            return null;
        }
        SysUser userById = userMapper.getUserById(id);
        // 加密身份证号
        String cardId = userById.getCardId();
        if(cardId != null){
            cardId = cardId.substring(0,4) + "********" + cardId.substring(cardId.length()-4,cardId.length());
            userById.setCardId(cardId);
        }
        return userById;
    }

    /**
     * 分页获取数据
     *
     * @param pageSize 每页显示条数
     * @param pageNum  当前页码
     * @return
     */
    @Override
    public IPage<SysUser> selectUserPage(Integer pageSize, Integer pageNum, Long userId, String query) {

        SysUser userById = getUserById(userId);

        Page<SysUser> page = new Page<>();
        // 设置当前页码
        page.setCurrent(pageNum);
        // 设置每页显示数据条数
        page.setSize(pageSize);
        // 分页查询数据
        return userMapper.selectUserPage(page, query, userById.getType());
    }

    /**
     * 更新用户信息
     *
     * @param user
     */
    @Override
    public SysUser updateUser(SysUser user) {
        if (ObjectUtil.isEmpty(user)) {
            return null;
        }
        // 判断身份证号是否被修改了
        if(ObjectUtil.isNotNull(user.getCardId()) && user.getCardId().contains("*")){
            user.setCardId(null);
        }
        // 更新用户信息
        int row = userMapper.updateById(user);
        // 更新用户角色表
        if (!ObjectUtil.isEmpty(user.getType())) {
            // 判断 角色id是否 为 null , 如果为null 说明不用更新
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(user.getType());
            // 构造更新条件, 根据用户id更新
            QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userRole.getUserId());
            userRoleMapper.update(userRole, queryWrapper);
        }
        // 查询更新后的数据
        return userMapper.getUserById(user.getId());
    }


    /**
     * 删除token
     *
     * @param token
     */
    @Override
    public void deleteToken(String token) {
        if (ObjectUtil.isNull(token)) {
            return;
        }
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("token", token);
        SysUser user = userMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotNull(user)) {
            // 将token设置为空
            user.setToken("");
            userMapper.updateById(user);
        } else {
            log.error("");
        }
    }

    /**
     * 更新用户状态
     *
     * @param userId
     * @param enabled
     * @return
     */
    @Override
    public Boolean updateUserStatus(Long userId, Integer enabled) {
        SysUser sysUser = new SysUser();
        sysUser.setId(Long.valueOf(userId));
        sysUser.setEnabled(enabled);
        int row = userMapper.updateById(sysUser);
        return row == 1;
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @Override
    public Boolean deleteUser(Long id) {

        // 1. 将用户从用户角色表中删除
        userRoleMapper.deleteByUserId(id);
        // 2. 将用户从用户表中删除
        int row = userMapper.deleteById(id);
        return row == 1;
    }

    /**
     * 更新用户角色
     *
     * @param userId
     * @param roleId
     */
    @Override
    public Boolean updateUserRole(Long userId, Long roleId) {
        // 更新用户表
        SysUser sysUser = new SysUser();
        sysUser.setId(userId);
        sysUser.setType(roleId);
        userMapper.updateById(sysUser);
        // 更新角色表
        int row = roleMapper.updateRoleByUserId(userId, roleId);
        return row == 1;
    }

    /**
     * 根据辖区获取对应辖区内的所有网格员
     *
     * @param address  辖区地址
     * @param roleName
     * @return
     */
    @Override
    public List<SysUser> getUserListByAddressAndRoleName(String address, String roleName) {
        List<SysUser> userListByAddressAndRoleName = userMapper.getUserListByAddressAndRoleName(address, roleName);
        return userListByAddressAndRoleName;
    }

    /**
     * 获取所有用户列表
     *
     * @return
     */
    @Override
    public List<SysUser> getUserList() {
        List<SysUser> sysUsers = userMapper.selectList(null);
        return sysUsers;
    }

    /**
     * 获取当前辖区的所有管理员用户
     *
     * @param userId
     * @return
     */
    @Override
    public List<SysUser> getAdminUserByArea(Long userId) {
        SysUser userById = userMapper.getUserById(userId);
        List<SysUser> sysUsers = userMapper.getAdminUserByArea(userById.getAddress(), RoleType.ADMIN, RoleType.SUPER_ADMIN);

        return sysUsers;
    }

    /**
     * 修改密码
     *
     * @param newPwd
     * @return
     */
    @Override
    public Boolean editPassword(String newPwd, Long id) {

        SysUser user = new SysUser();
        String encode = PasswordEncodeUtil.encode(newPwd);
        user.setId(id);
        user.setPassword(encode);

        try {
            return userMapper.updateById(user) !=0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
